#define _CRT_SECURE_NO_WARNINGS 1

#include"Head.h"

void HeapInit(Heap* hp)
{
	assert(hp);
	hp->a = NULL;
	hp->capacity = 0;
	hp->size = 0;
}

void HeapDestory(Heap* hp)
{
	assert(hp);
	free(hp->a);
	hp->a = NULL;
	hp->capacity = 0;
	hp->size = 0;
}

void swap(int* a,int* b)
{
	HPDataType c = *a;
	*a = *b;
	*b = c;
}



void HeapPush(Heap* hp, HPDataType x)
{
	assert(hp);
	if (hp->size == hp->capacity)
	{
		size_t newcapacity = hp->capacity == 0 ? 4 : hp->capacity * 2;
		int* a = realloc(hp->a, sizeof(HPDataType) * newcapacity);
		if (a == NULL)
		{
			perror("realloc fail");
			return;
		}
		hp->a = a;
		hp->capacity = newcapacity;
	}
	hp->a[hp->size] = x;
	int child = hp->size;
	int parent = (child - 1) / 2;
	hp->size++;
	while (child > 0)
	{
		if (hp->a[child] < hp->a[parent])
		{
			swap(&hp->a[child], &hp->a[parent]);
			child = parent;
			parent = (parent - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void HeapPop(Heap* hp)
{
	assert(hp);
	swap(&hp->a[0], &hp->a[--hp->size]);
	int parent = 0;
	int child = parent * 2 + 1;
	if (child+1 < hp->size && hp->a[child] > hp->a[child+1])
	{
		child += 1;
	}
	while (child < hp->size && hp->a[parent]>hp->a[child])
	{
		swap(&hp->a[child], &hp->a[parent]);
		parent=child;
		child = parent * 2 + 1;
		if (child + 1 < hp->size && hp->a[child] > hp->a[child + 1])
		{
			child += 1;
		}
	}
}

HPDataType HeapTop(Heap* hp)
{
	assert(hp);
	assert(hp->a);
	return hp->a[0];
}

int HeapSize(Heap* hp)
{
	assert(hp);
	return hp->size;
}

int HeapEmpty(Heap* hp)
{
	assert(hp);
	return hp->size == 0;
}